package com.daniel.stream;

import com.daniel.po.StudentsPO;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.Test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 集合的流操作
 * @Author GanShaoXi
 * @ClassName CollectionStreamOperate
 * @Return com.daniel.stream
 * @Since 1.0.0
 * @Created on 2023/7/10 20:15
 */
@Slf4j
public class CollectionStreamOperate {
    @Test
    public void testStreamCollection() {
        List<StudentsPO> list1 = Lists.newArrayList();
        for (int i = 1; i <= 20; i++) {
            StudentsPO studentsPO = new StudentsPO();
            studentsPO.setId(i);
            studentsPO.setName("Daniel" + i);
            studentsPO.setSex(23);
            studentsPO.setEmail(i + "11111111@email.com");
            list1.add(studentsPO);
        }
        List<StudentsPO> list2 = Lists.newArrayList();
        for (int i = 16; i <= 35; i++) {
            StudentsPO studentsPO = new StudentsPO();
            studentsPO.setId(i);
            studentsPO.setName("Daniel" + i);
            studentsPO.setSex(24);
            studentsPO.setEmail(i + "222222222@email.com");
            list2.add(studentsPO);
        }
        // 取交集(list1和list2中都有的元素)
        List<StudentsPO> filter1 = list1.stream().filter(
                item -> list2.stream().map(StudentsPO::getId).collect(Collectors.toList()).contains(item.getId())).collect(Collectors.toList());

        // 取差集(只有list1中有的元素，换句话说从list1中移除含有list2的元素)
        List<StudentsPO> filter2 = list1.stream().filter(
                item -> !list2.stream().map(StudentsPO::getId).collect(Collectors.toList()).contains(item.getId())).collect(Collectors.toList());

        log.info("filter1.size = {},filter1.toString() = {}", filter1.size(), filter1);
        log.info("filter2.size = {},filter2.toString() = {}", filter2.size(), filter2);

        list1.addAll(list2);
        //  去重（去除list中重复元素）
        List<StudentsPO> result = list1.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(StudentsPO::getId))), ArrayList::new));
        log.info("result.size = {},result.toString() = {}", result.size(), result);
        log.info("list1.size = {},list1 = {}", list1.size(), list1);
        log.info("list2.size = {},list2 = {}", list2.size(), list2);

        Map<Integer, Integer> groupBy = list1.stream().collect(Collectors.groupingBy(StudentsPO::getSex, Collectors.summingInt(item -> 1)));
        System.out.println("groupBy = " + groupBy);

    }
}
